package com.zy.explore.idempotent.interfaces.facade.v1;

import com.alibaba.fastjson.JSON;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.zy.explore.idempotent.application.service.RedisService;
import com.zy.explore.idempotent.application.service.TokenService;
import com.zy.explore.idempotent.interfaces.frm.CommonStringIdFrm;
import com.zy.explore.idempotent.interfaces.frm.ExampleFrm;
import com.zy.explore.idempotent.interfaces.vo.ExampleVO;
import com.zy.explore.idempotent.interfaces.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * description Redis示例Facade
 *
 * @author ZY
 * @date 2021年05月20日 23:09
 */
@Api(tags = "Redis示例Facade")
@RestController
@RequestMapping("/redis")
public class RedisExampleFacade {

    /**
     * 注入服务
     */
    @Resource
    private RedisService service;

    @Resource
    private TokenService tokenService;

    /**
     * 新增数据
     *
     * @param frm 待新增的Frm对象
     * @return 成功返回新增后的VO对象，失败返回null
     */
    @ApiOperationSupport(order = 10)
    @ApiOperation("新增数据")
    @PostMapping("/insert")
    public ResultVO<ExampleVO> insert(@RequestBody ExampleFrm frm) {
        if (!StringUtils.isEmpty(frm.getId())) {
            this.service.set(frm.getId(), JSON.toJSONString(frm));
        }
        return ResultVO.getSuccess();
    }

    /**
     * 删除数据
     *
     * @param frm 主键Frm对象
     * @return 1:删除成功 其他:删除失败
     */
    @ApiOperationSupport(order = 20)
    @ApiOperation("删除数据")
    @PutMapping("/delete")
    public ResultVO<Integer> delete(@RequestBody CommonStringIdFrm frm) {
        this.service.del(frm.getId());
        return ResultVO.getSuccess();
    }


    /**
     * 通过主键查询单条数据
     *
     * @param frm 主键Frm对象
     * @return 成功返回对应ID的VO对象，查询不到返回null
     */
    @ApiOperationSupport(order = 30)
    @ApiOperation("根据主键查询数据")
    @GetMapping("/findById")
    public ResultVO<Object> findById(@SpringQueryMap CommonStringIdFrm frm) {
        Object o = this.service.get(frm.getId());
        return ResultVO.getSuccess(o);
    }

    /**
     * 获取幂等令牌
     *
     * @return {@link ResultVO<String>}
     */
    @ApiOperationSupport(order = 40)
    @ApiOperation("创建幂等令牌")
    @GetMapping("/getIdempotentToken")
    public ResultVO<String> getIdempotentToken() {
        return ResultVO.getSuccess(tokenService.createToken());
    }

}
